import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import home from "../views/Home.vue";
import { useToastStore } from "@/store/showToast"; //提示-pinia

//2.进行路由配置
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/home",
  },
  // 首页
  {
    path: "/home",
    name: "home",
    component: () => import("@/views/Home.vue"),
  },
  {
    path: "/goods",
    name: "goods",
    component: () => import("@/views/Goods.vue"),
  },
  {
    path: "/user",
    name: "user",
    redirect: "/user/cart",
    component: () => import("@/views/User.vue"),
    children: [
      { path: "cart", component: () => import("@/components/cart/cart.vue") },
    ],
  },
  {
    path: "/order",
    name: "order",
    component: () => import("@/views/Order.vue"),
  },
  {
    path: "/free",
    name: "free",
    component: () => import("@/views/Free.vue"),
  },
  {
    path: "/details",
    name: "details",
    component: () => import("@/views/Details.vue"),
  },
  //404页面
  {
    path: "/error",
    name: "error",
    component: () => import("@/components/error/error.vue"),
  },
  // 地址错误就会出现404页面
  //匹配所用路径：vue2使用*,vue3使用/:pathMatch(.*)*或/:pathMatch(.*)或/:catchAll(.*)
  {
    path: "/:catchAll(.*)", // 不识别的path自动匹配404
    redirect: "/error",
  },
];

//1.创建路由对象
const router = createRouter({
  routes,
  //3.指定路由模式
  history: createWebHashHistory(),
});

//全局前置守卫
router.beforeEach((to, from, next) => {
  const useToast = useToastStore(); //提示框-pinia
  //验证进入个人中心页面时，如果没有登录给与提示先登录
  if (to.path == "/user/cart") {
    let token = localStorage.getItem("token");
    if (!token) {
      //提示登录
      useToast.ToastShowModel({
        isShow: true,
        msg: "请先登录",
        type: "error",
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
